package com.lhfeiyu.action.front.chat;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.po.AuctionMicro;
import com.lhfeiyu.po.WxMsgCount;
import com.lhfeiyu.po.base.BaseFans;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.service.AuctionMicroService;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.WxMsgCountService;
import com.lhfeiyu.service.base.BaseFansService;
import com.lhfeiyu.service.base.BaseGoodsService;
import com.lhfeiyu.thirdparty.wx.business.MessageNews;
import com.lhfeiyu.thirdparty.wx.business.New;
import com.lhfeiyu.thirdparty.wx.business.News;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;

@Controller
public class WxMsgCountAction {
	@Autowired
	private WxMsgCountService wxMsgCountService;
	@Autowired
	private AuthCheckService authCheckService;
	@Autowired
	private BaseFansService fansService;
	@Autowired
	private BaseGoodsService goodsService;
	@Autowired
	private AuctionMicroService auctionMicroService;
	
	private static Logger logger = Logger.getLogger("R");
	
	@RequestMapping(value="/wxMsgCount")
	public ModelAndView collectGoods(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.wxMsgCount;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/wxMsgCount";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			Integer userId = sessionUser.getId();
			Map<String,Object> map = CommonGenerator.getHashMap();
			map.put("userId", userId);
			map.put("sendDate",new Date());
			WxMsgCount wxMsgCount = wxMsgCountService.selectByCondition(map);
			if(null != wxMsgCount){
				modelMap.put("wxMsgCount", wxMsgCount);
			}
			modelMap.put("userId", userId);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/wxMsgCount", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@ResponseBody
	@RequestMapping(value="/addOrUpdateWxMsgCount", method=RequestMethod.POST)
	public JSONObject addOrUpdateWxMsgCount(@ModelAttribute WxMsgCount wxMsgCount, HttpServletRequest request){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			String r = user.getSerial();
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			List<BaseFans> db_fansList = fansService.selectListByCondition(map);
			if(null == db_fansList || db_fansList.size() < 0){
				json.put("status", "failure");
				json.put("msg", "您当前还没有粉丝，无法群发消息.");
				return Result.success(json);
			}
			map.clear();
			String amIds = request.getParameter("goodsIds");
			map.put("goodsIds", amIds);
			List<AuctionMicro> amList = auctionMicroService.selectListByCondition(map);
			if(null == amList || amList.size() < 0){
				json.put("status", "failure");
				json.put("msg", "您当前还没有参与微拍，无法群发消息给粉丝.");
				return Result.success(json);
			}
			
			wxMsgCount.setUserId(user.getId());
			wxMsgCount.setMsgType(1);
			wxMsgCount.setCount(1);
			wxMsgCount.setMaxCount(3);
			wxMsgCount.setCreatedBy(user.getUsername());
			wxMsgCount.setCreatedAt(new Date());
			
			
			
			Integer wxMsgCountId = wxMsgCount.getId();
			WxMsgCount db_wxMsgCount = wxMsgCountService.selectByPrimaryKey(wxMsgCountId);
			if(null != db_wxMsgCount){
				if(db_wxMsgCount.getCount() < 3 && db_wxMsgCount.getCount() >= 1){
					Integer count = db_wxMsgCount.getCount();
					Integer maxCount = db_wxMsgCount.getMaxCount();
					wxMsgCount.setCount(++count);
					wxMsgCount.setMaxCount(--maxCount);
				}else{
					json.put("msg", "每天最多只能发3次群发信息");
					return Result.failure(json, "每天最多只能发3次群发信息", "每天最多只能发3次群发信息");
				}
			}
			wxMsgCount.setSendDate(new Date());
			wxMsgCountService.insert(wxMsgCount);
			
			json.put("status", "success");
			json.put("id",wxMsgCount.getId());
			json.put("msg", "操作成功");
			
			if(null != amList && !"".equals(amList)){
				MessageNews mn = new MessageNews();
				mn.setMsgtype("news");
				News news = new News();
				List<New> articles = new ArrayList<New>();
				if(null != amList){
					if(amList.size() > 0){
						for(AuctionMicro am:amList){
							//System.out.println(am);
							New n = new New();
							String description = am.getGoodsDescription();
							String picUrl =am.getPicPath();
							String title = am.getGoodsName();
							///goods/1?shopId=8&r=u201601910214097
							String url = "http://weipaike.net/am?amSerial="+am.getSerial();
							if(null != r){
								url += "&r="+r;
							}
							if(null != description){
								n.setDescription(description);
							}else{
								n.setDescription("暂无商品描述");
							}
							n.setPicurl(picUrl);
							n.setTitle(title);
							n.setUrl(url);
							articles.add(n);
						}
					}
				}
				news.setArticles(articles);
				mn.setNews(news);
				map.clear();
				map.put("userId", userId);
				List<BaseFans> baseDb_fansList = fansService.selectListByCondition(map);
				if(null != baseDb_fansList){
					if(baseDb_fansList.size() > 0){
						for(BaseFans f:baseDb_fansList){
							//System.out.println("000:"+f);
							mn.setTouser(f.getWxOpenid());
							com.lhfeiyu.thirdparty.wx.business.Message.sendKFMessage(mn);
						}
					}
				}
			}
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/wxMsgCount", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getWxMsgCountList", method=RequestMethod.POST)
	public JSONObject getWxMsgCountList(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == sessionUser){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Map<String, Object> map = ActionUtil.getAllParam(request);
			wxMsgCountService.getWxMsgCountList(json, map);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/getWxMsgCountList", json);
		}
		return Result.success(json);
	}
	
}
